// pages/meetest/meetest.js
const db = wx.cloud.database()
const openid = 'ohg9a5NAOdZbTKcIlB_1dT3_5vxM'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    buttonStyle: 'button-enable',
    curr_month: new Date().getMonth() + 1,
    sele_month: 9,
    curr_day: new Date().getDate(),
    curr_user:'',
    curr_depart:'',
    sele_day: 0,
    date:'',
    currmeet: '1号',
    dayStyle: [
      { month: 'current', day: new Date().getDate(), color: 'white', background: '#AAD4F5' },
      { month: 'current', day: new Date().getDate(), color: 'white', background: '#AAD4F5' },
    ],
    room: [], //会议室
    list: [], //预订部门
    //声明json对象，存放日期样式；
    datas: {
      month: 'current',
      day: new Date().getDate(),
      color: 'white',
      background: '#AAD4F5'
    },
    listtimes: [],
    starttimes:[],
    endtimes:[9,10],
    st: 8,
    et: 9,
    index: 0,
    indx: 0,
    ih:0,
    im:0
  },
  

  //给点击的日期设置一个背景颜色
  dayClick: function (event) {
    this.setInitData(event);
    
    //判断是否预订
    if (this.ishas(this.data.sele_day)) {
      wx.showModal({
        title: '提示',
        content: '已预订',
      });
      this.setData({
        date:'',
        have:''
      })
      return;
    }

    if (this.data.sele_month >= this.data.curr_month) {
      if (this.data.sele_month == this.data.curr_month) {
        if (this.data.curr_day > this.data.sele_day) {
          wx.showModal({
            title: '提示',
            content: '日期不能小于当前',
          });
          this.setData({
            date:'',
            have: ''
          })
          return
        }
      }
      //获取日期
      this.getCurrentDate(event);
      this.hasdata();

      //this.setStyle();
    }
    else {
      wx.showModal({
        title: '提示',
        content: '请选择当月或之后的日期',
      })
      this.setData({
        date:'',
        have: ''
      })
    }
  },

  //判断是上午，下午，全天
  gettime(datetime) {
    let vars = []
    let result ='';
    vars = datetime.split('-');
    let n1 = parseInt(vars[0]);
    let n2 = parseInt(vars[1]);
    if(n1< 13&& n2<= 13)
    {
      result ='上午';
    }else if(n1>=13&& (n2>=13&& n2<=19))
    {
         result='下午'
    }
    else if(n1<11 && n2>13)
    {
      result='全天'
    }
    return result
  },


  //判断选择日期的背景色；
  ishas(day) {
    let iday = this.data.dayStyle[0]['day']
    let color = this.data.dayStyle[0]['background']

    let isa = false
    for (let i = 0; i < this.data.dayStyle.length; i++) {
      iday = this.data.dayStyle[i]['day']
      color = this.data.dayStyle[i]['background']
      if (day == iday && color == '#ff0000') {
        isa = true;
      }
    }
    return isa;
  },
  //已预订消息,根据日期+会议室获取上午或下午已选择的时间点;
  hasdata(){
    db.collection('meetab').where({
      _openid: openid //app.globalData.projectid 
    }).where({
      date:this.data.date
    }).where({
      meet: this.data.room[this.data.index]
    }).field({
       time:true
    }).get().then(res=>{
     
      if(res.data.length > 0)
      {
        this.setData({
          have: "**"+this.data.sele_day+"日已预订" + res.data[0]['time']
        })
      }
      else
      {
        this.setData({
          have: ""
        })
      }
     
    }).catch(err=>{
      console.log(err);
    })
  },

  //初始化数据;
  setInitData(event) {
    this.setData({
      //获取当前月份;
      curr_month: new Date().getMonth() + 1,
      //获取当前日期;
      curr_day: new Date().getDate(),
      //手动点击月份
      sele_month: event.detail.month,
      //手动点日期;
      sele_day: event.detail.day
    });
  },
  //初始化数据---获取会议起止时间;
  onInitData(){
    var that = this;
    var res = wx.getStorageSync('userinfo');
    console.log('onInitData',res)
    this.setData({
      curr_depart: res.depart
    })
    this.setData({
      curr_user: res.username
    })


    //初始化起止时间
    for(let i= this.data.st;i<=20;i++)
    {
      that.setData({
        starttimes: that.data.starttimes.concat(i)
      })
    }
   
    //取消起止时间列表;
    // db.collection("times").where({
    //   _openid: openid
    // }).get().then(res=>{
    //   for(let i=0; i< res.data.length;i++)
    //   {
    //     var sstime = res.data[i]['stime'];
    //     this.setData({
    //       listtimes: this.data.listtimes.concat(sstime)
    //     })
    //   }
    // }).catch(err=>{
    //   console.log(err);
    // });
    this.initMeetRoom();
    //初始化部门；
    db.collection("departs").where({
      _openid: openid //app.globalData.projectid 
    }).get().then(res => {
      for (let i = 0; i < res.data.length; i++) {
        var temp = res.data[i]['depart'];
        that.setData({
          list: that.data.list.concat(temp)
        })
        //获取预订人所在部门
        if(this.data.curr_depart==temp)
        {
          that.setData({
            indx:i
          })
        }
      }
    }).catch(err => {
      console.log(err);
    })
  },
   
  //初始化会议室信息;
  initMeetRoom()
  {
    this.data.room.length =0;
    db.collection("meeting").where({
      _openid: openid //app.globalData.projectid 
    }).get().then(res => {
      for (let i = 0; i < res.data.length; i++) {
        var meet = res.data[i]['meet'];
        this.setData({
          room: this.data.room.concat(meet)
        })
      }
      //console.log('init meeting', this.data.array);
      this.setData({
        currmeet: this.data.room[0]
      })
      //console.log('init currmeet', this.data.currmeet)
    }).catch(err => {
      console.log(err);
    })
  },
  
  //初始化样式,根据会议室+月份获取日期样式；
  setStyle: function(){
    this.setData({
      dayStyle: [
        { month: 'current', day: new Date().getDate(), color: 'white', background: '#AAD4F5' },
        { month: 'current', day: new Date().getDate(), color: 'white', background: '#AAD4F5' },
      ]
    });

    let n =0;
    db.collection("dayStyle").where({
      _openid: app.globalData.projectid 
    }).where({
      months: this.data.sele_month
      }).where({
        meet: this.data.currmeet //this.data.room.length?0: that.data.room[that.data.index]
    }).orderBy('day','asc').get().then(res => {
      n = res.data.length-1;
      
      for (let i = 0; i < res.data.length; i++) {
        this.setData({
          datas: {
            month: 'current',
            day: res.data[i]['day'],
            color: 'white',
            background: res.data[i]['background']
          },
        })
        this.setData({
          dayStyle: this.data.dayStyle.concat(this.data.datas)
        })
      }
      // console.log('n=',n)
      // console.log(this.data.dayStyle);
      // console.log('setStyle', res.data);
      if(n > 1)
      {
        this.setData({
          datas: {
            month: 'current',
            day: res.data[n]['day'],
            color: 'white',
            background: res.data[n]['background']
          },
          dayStyle: this.data.dayStyle.concat(this.data.datas)
        })
      }
    }).catch(err => {
      console.log(err);
    })
  },

  //获取选中日期
  getCurrentDate(event) {
    let clickDay = event.detail.day;
    let changeDay = `dayStyle[1].day`;
    let changeBg = `dayStyle[1].background`;
    this.setData({
      [changeDay]: clickDay,
      [changeBg]: "#84e7d0",
      date: event.detail.year + '-' + event.detail.month + '-' + event.detail.day
    });
  },
  //选择会议室;
  listenerPickerSelected: function (e) {
    //改变index值，通过setData()方法重绘界面
    this.setData({
      index: e.detail.value
    });
    this.setData({
      currmeet: this.data.room[this.data.index]
    });
    this.setStyle();
  },

  onChange: function (event) {
    console.log(event);
  },
  //部门选择
  departSelected: function (e) {
    this.setData({
      indx: e.detail.value
    })
  },
  /**
 * 监听时间picker选择器
 */
  startTimePickerSelected: function (e) {
    //调用setData()重新绘制 
    this.setData({
      ih: e.detail.value
    });
    this.setData({
      et: this.data.starttimes[this.data.ih] + 1
    })
    this.data.endtimes.length =0
    for (let j = this.data.et; j <= 24; j++) {
      this.setData({
        endtimes: this.data.endtimes.concat(j)
      })
    }
  },
  endTimePickerSelected: function (e) {
    this.setData({
      im: e.detail.value
    })
  },

  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    });
  },
  //提交记录;
  onSave:function(){
    if (this.data.date.length == 0)
    {
      wx.showModal({
        title: '提示',
        content: '请选择会议日期!',
      })
      return;
    }
    if(this.data.curr_user.length ==0)
    {
      wx.showModal({
        title: '提示',
        content: '预订人不能为空!',
      })
      return;
    }
    if (this.data.list.length == 0) {
      wx.showModal({
        title: '提示',
        content: '部门不能为空!',
      })
      return;
    }
    let id ='';
    let vflag = this.gettime(this.data.starttimes[this.data.ih] + ":00-" + this.data.endtimes[this.data.im] + ":00");
    db.collection('meetab').add({
      data:{
        user: this.data.curr_user,
        depart: this.data.list[this.data.indx],
        meet: this.data.room[this.data.index],
        date: this.data.date,
        date2: this.data.sele_month+'月'+this.data.sele_day,
        year: new Date().getFullYear,
        month: this.data.sele_month,
        flag: vflag, 
        time: this.data.starttimes[this.data.ih]+":00-"+this.data.endtimes[this.data.im]+":00"
      }
    }).then(res=>{
      //提交成功后，保存日期样式；
      console.log('add meeting data success!!!');
      id = res._id;
      let color ="#ff0000";
      switch(vflag)
      {
        case "上午":
          color ="#00FF00";
        break;
        case "下午":
          color ="#FF33FF";
        break;
        case "全天":
          color = "#ff0000";
        break;
      }
      db.collection('dayStyle').add({
        data:{
          styleid: id,
          meet: this.data.room[this.data.index],
          month: 'current',
          day: this.data.sele_day,
          months: this.data.sele_month,
          color: 'white',
          background: color //'#ff0000'
        }
      }).then(ress=>{
        this.setData({
          date:''
        })
        console.log('add dayStyle success!!!');
        wx.showToast({
          title: '提交成功！',
        })
        //提交完后，重置样式；
        this.setStyle();
      }).catch(err=>{
        console.log('add dayStyle Error',err)
      })
    })
    .catch(err=>{
       console.log(err);
    })
  },

  gotoList:function(){
    var res = wx.getStorageSync('userinfo')
    console.log('gotolist',res)
    if (res != null)
    {
      var tem = res.username
      wx.showModal({
        title: 'xxx',
        content: tem,
      })
    }
 
  
  //  wx.navigateTo({
  //    url: '../meetlist/meetlist',
  //    success: function(res) {
  //       console.log('navigateToe success',res);
  //    },
  //    fail: function(res) {
  //      console.log('navigateTo err...',res);
  //    },
  //    complete: function(res) {},
  //  })
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.onInitData();
    that.setStyle();

    //页面加载后，部分日期背景颜色变红;
    // this.setData({
    //   dayStyle: [
    //     { month: 'current', day: new Date().getDate(), color: 'white', background: '#AAD4F5' },
    //     { month: 'current', day: 18, color: 'white', background: '#ff0000' },
    //     { month: 'current', day: 26, color: 'white', background: '#ff0000' },
    //     { month: 'current', day: 30, color: 'white', background: '#ff0000' },
    //   ]
    // })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var array = that.data.list;
    var res = wx.getStorageSync('userinfo');
    // console.log('onshow-res缓存信息', res);
    // console.log('onshow-array部门列表', array);
    if(res != null)
    {
      let temp_deparpt = res.depart;
      that.setData({
        curr_user: res.username
      })
     
      for (var i = 0; i < array.length; i++) {
        //获取预订人所在部门
        if (temp_deparpt == array[i]) {
          that.setData({
            indx: i
          })
        }
      }
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})